package com.kele.auth.controller;

import com.kele.base.model.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.Map;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2023/4/24 13:52
 * @Version:
 */
@RestController
@RequestMapping("/oauth")
public class LoginController {

    //令牌请求的端点
    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;
    @Resource
    private ConsumerTokenServices consumerTokenServices;

    /**
     * 重写/oauth/token这个默认接口，返回的数据格式统一
     */
    @PostMapping(value = "/token")
    public ResponseResult postAccessToken(Principal principal, @RequestParam
            Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return ResponseResult.success(accessToken);
    }

    @GetMapping("/check_token")
    public ResponseResult checkToken(@RequestParam("token") String value){
        Map<String, ?> stringMap = checkTokenEndpoint.checkToken(value);
        return ResponseResult.success(stringMap);
    }

    @PostMapping("/logout")
//    public ResponseResult logout(@RequestHeader("Authorization")String accessToken){
    public ResponseResult logout(){
        String accessToken = " 121";
        String token = accessToken.split(" ")[1];
        if (consumerTokenServices.revokeToken(token)) {
            return ResponseResult.success();
        }
        return ResponseResult.fail("注销失败");
    }
}
